<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->
        <el-input v-model="query.workOrderCode" clearable placeholder="工单编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-input v-model="query.orderCode" clearable placeholder="订单编号" style="width: 185px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select
          v-model="query.productType"
          clearable
          filterable
          placeholder="产品类型"
          style="width: 185px;"
          class="filter-item"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in productTypes"
            :key="item.id"
            :label="item.productTypeName"
            :value="item.productType"
          >
            <span style="float: left">{{ item.productTypeName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.productType }}</span>
          </el-option>
        </el-select>
        <el-select
          v-model="query.productCode"
          clearable
          filterable
          placeholder="产品型号"
          style="width: 220px;"
          class="filter-item"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in products"
            :key="item.id"
            :label="item.productName"
            :value="item.productCode"
          >
            <span style="float: left">{{ item.productName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.productCode }}</span>
          </el-option>
        </el-select>

        <el-select
          v-model="query.lineCode"
          clearable
          filterable
          placeholder="产线编号"
          style="width: 220px;"
          class="filter-item"
          @change="lineCodeChange"
        >
          <el-option
            v-for="item in lines"
            :key="item.id"
            :label="item.modelName"
            :value="item.modelCode"
          >
            <span style="float: left">{{ item.modelName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
          </el-option>
        </el-select>

        <el-select
          v-model="query.sectionCode"
          clearable
          filterable
          placeholder="工段编号"
          style="width: 220px;"
          class="filter-item"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in sections"
            :key="item.id"
            :label="item.modelName"
            :value="item.modelCode"
          >
            <span style="float: left">{{ item.modelName }}</span>
            <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
          </el-option>
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="800px">
        <el-form :inline="true" ref="form" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="工单编号" prop="workOrderCode">
            <el-input v-model="form.workOrderCode" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="关联订单" >
            <el-select   v-model="form.orderCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in orders"
                :key="item.id"
                :label="item.orderCode"
                :value="item.orderCode" >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产线编号" prop="lineCode">
            <el-select @change="lineCodeChange" v-model="form.lineCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in lines"
                :key="item.id"
                :label="item.modelName"
                :value="item.modelCode" >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="工段编号" prop="sectionCode">
            <el-select @change="sectionCodeChange" v-model="form.sectionCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in sections"
                :key="item.id"
                :label="item.modelName"
                :value="item.modelCode" >
                <span style="float: left">{{ item.modelName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.modelCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
<!--          <el-form-item label="产品类型">
            <el-input v-model="form.productType" style="width: 285px;" />
          </el-form-item>-->
          <el-form-item label="产品型号" prop="productCode">
            <el-select @change="productCodeChange" v-model="form.productCode" style="width: 285px" filterable placeholder="请选择">
              <el-option
                v-for="item in crudProducts"
                :key="item.id"
                :label="item.productName"
                :value="item.productCode" >
                <span style="float: left">{{ item.productName }}</span>
                <span style="float: right; color: #8492a6; font-size: 13px">{{ item.productCode }}</span>
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="需求数量" prop="requiredQty">
            <el-input-number style="width: 285px;" v-model="form.requiredQty" :step="1" step-strictly></el-input-number>
          </el-form-item>
          <el-form-item label="计划开始" prop="planStart">
            <el-date-picker v-model="form.planStart" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="计划结束" prop="planEnd">
            <el-date-picker v-model="form.planEnd" value-format="yyyy-MM-dd HH:mm:ss" type="datetime" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="计划员" prop="planner">
            <el-input v-model="form.planner" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="客户名称" prop="clientName">
            <el-input v-model="form.clientName" style="width: 285px;" />
          </el-form-item>
          <el-form-item label="描述">
            <el-input v-model="form.remark" :rows="3" type="textarea" style="width: 670px;" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>

      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane name="0" >
          <span slot="label">
            未下发 <el-badge :value="statusCount['0'] ? statusCount['0'] : 0" type="info"></el-badge>
          </span>
        </el-tab-pane>
        <el-tab-pane name="1">
          <span slot="label">
            已停止 <el-badge :value="statusCount['1'] ? statusCount['1'] : 0" type="warning"></el-badge>
          </span>
        </el-tab-pane>
        <el-tab-pane name="2" >
          <span slot="label">
            生产中 <el-badge :value="statusCount['2'] ? statusCount['2'] : 0" type="primary"></el-badge>
          </span>
        </el-tab-pane>
        <el-tab-pane name="3" >
          <span slot="label">
            已完成 <el-badge :value="statusCount['3'] ? statusCount['3'] : 0" type="success"></el-badge>
          </span>
        </el-tab-pane>
      </el-tabs>
      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="orderCode" label="订单编号" width="120px;" align="center"/>
        <el-table-column prop="workOrderCode" label="工单编号" width="120px;" align="center"/>
        <el-table-column prop="orderStatus" label="工单状态" width="100px;" align="center">
          <template slot-scope="scope">
            <el-tag :type="getOrderStatusColour(scope.row.orderStatus)">{{ dict.label.work_order_status[scope.row.orderStatus] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productCode" label="产品型号" width="120px;" align="left"/>
        <el-table-column prop="productType" label="产品类型" width="80px;" align="center">
          <template slot-scope="scope">
            {{ getProductTypeName(scope.row.productType) }}
          </template>
        </el-table-column>
        <el-table-column prop="requiredQty" label="需求数量" width="100px;" align="center"/>
        <el-table-column prop="totalQty" label="总数量" width="100px;" align="center"/>
        <el-table-column prop="finishQty" label="完成数量" width="100px;" align="center"/>
        <el-table-column prop="failQty" label="失败数量" width="100px;" align="center"/>
        <el-table-column prop="onlineQty" label="在线数量" width="100px;" align="center"/>
        <el-table-column prop="scrapQty" label="报废数量" width="100px;" align="center"/>
        <el-table-column prop="unfinishQty" label="未完成数量" width="100px;" align="center"/>
        <el-table-column prop="clientName" label="客户名称" width="150px;" align="center"/>
        <el-table-column prop="planner" label="计划员" width="100px;" align="center" />
        <el-table-column prop="lineCode" label="产线编号" width="150px;" align="center"/>
        <el-table-column prop="sectionCode" label="工段编号" width="150px;" align="center"/>
        <el-table-column prop="planStart" label="计划开始" width="150px;" align="center"/>
        <el-table-column prop="planEnd" label="计划结束" width="150px;" align="center"/>
        <el-table-column prop="practicalStart" label="实际开始时间" width="150px;" align="center"/>
        <el-table-column prop="practicalEnd" label="实际结束时间" width="150px;" align="center"/>
        <el-table-column prop="remark" label="描述" width="250px;" align="center"/>
        <el-table-column prop="createBy" label="创建人" width="100px;" align="center"/>
        <el-table-column prop="createTime" label="创建时间" width="150px;" align="center"/>
        <el-table-column prop="updateBy" label="更新人" width="100px;" align="center"/>
        <el-table-column prop="updateTime" label="更新时间" width="150px;" align="center"/>
        <el-table-column v-if="checkPer(['admin','planWorkOrder:edit','planWorkOrder:del'])" fixed="right" label="操作" width="280px" align="center">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            >
              <el-button v-if="scope.row.orderStatus != '2' " slot="view" type="primary" style="margin-right:3px;" @click="updateOrderStatus('2',scope.row)" size="mini">开始</el-button>
              <el-button v-if="scope.row.orderStatus == '2'" slot="view" type="warning" style="margin-right:3px;" @click="updateOrderStatus('1',scope.row)" size="mini">停止</el-button>
              <el-button v-if="scope.row.orderStatus == '2'" slot="view" type="success" style="margin-right:3px;" @click="updateOrderStatus('3',scope.row)" size="mini">完成</el-button>
            </udOperation>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import crudPlanWorkOrder from '@/api/plan/planWorkOrder'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import crudProductType from "@/api/product/productType";
import crudProductModel from "@/api/product/productModel";
import crudFactoryModel from "@/api/factory/factoryModel";
import crudProductModelLien from "@/api/product/productModelLien";
import crudPlanOrder from '@/api/plan/planOrder'

const defaultForm = { id: null, workOrderCode: null, orderCode: null, orderStatus: '0', productCode: null, productType: null, requiredQty: null, lineCode: null, sectionCode: null, planStart: null, planEnd: null, practicalStart: null, practicalEnd: null, clientName: null, planner: null, totalQty: 0, finishQty: 0, failQty: 0, onlineQty: 0, scrapQty: 0, unfinishQty: 0, remark: null, createBy: null, createTime: null, updateBy: null, updateTime: null }
export default {
  name: 'PlanWorkOrder',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['work_order_status'],
  cruds() {
    return CRUD({
      title: '工单管理',
      url: 'api/planWorkOrder',
      idField: 'id',
      sort: 'id,desc',
      optShow: {
        add: true,
        edit: true,
        del: true,
        download: false,
        reset: true,
        import: true
      },
      crudMethod: { ...crudPlanWorkOrder }})
  },
  data() {
    return {
      activeName: '0',
      productTypes: [],
      products: [],
      crudProducts:[],
      lines: [],
      orders: [],
      sections: [],
      statusCount: {},
      permission: {
        add: ['admin', 'planWorkOrder:add'],
        edit: ['admin', 'planWorkOrder:edit'],
        del: ['admin', 'planWorkOrder:del']
      },
      rules: {
        workOrderCode: [
          { required: true, message: '工单编号不能为空', trigger: 'blur' }
        ],
        orderCode: [
          { required: true, message: '订单编号不能为空', trigger: 'blur' }
        ],
        orderStatus: [
          { required: true, message: '订单状态不能为空', trigger: 'blur' }
        ],
        productCode: [
          { required: true, message: '产品型号不能为空', trigger: 'blur' }
        ],
        sectionCode: [
          { required: true, message: '工段不能为空', trigger: 'blur' }
        ],
        requiredQty: [
          { required: true, message: '需求数量不能为空', trigger: 'blur' }
        ],
        lineCode: [
          { required: true, message: '产线编号不能为空', trigger: 'blur' }
        ],
        planStart: [
          { required: true, message: '计划开始不能为空', trigger: 'blur' }
        ],
        planEnd: [
          { required: true, message: '计划结束不能为空', trigger: 'blur' }
        ],
        planner: [
          { required: true, message: '计划员不能为空', trigger: 'blur' }
        ],
        clientName: [
          { required: true, message: '客户名称不能为空', trigger: 'blur' }
        ],
        orderSorts: [
          { required: true, message: '订单来源不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'id', display_name: 'ID' },
        { key: 'workOrderCode', display_name: '工单编号' },
        { key: 'orderCode', display_name: '订单编号' },
        { key: 'orderStatus', display_name: '工单状态' },
        { key: 'productCode', display_name: '产品型号' },
        { key: 'productType', display_name: '产品类型' },
        { key: 'requiredQty', display_name: '需求数量' },
        { key: 'lineCode', display_name: '产线编号' },
        { key: 'sectionCode', display_name: '工段编号' },
        { key: 'planStart', display_name: '计划开始' },
        { key: 'planEnd', display_name: '计划结束' },
        { key: 'practicalStart', display_name: '实际开始时间' },
        { key: 'practicalEnd', display_name: '实际结束时间' },
        { key: 'clientName', display_name: '客户名称' },
        { key: 'planner', display_name: '计划员' },
        { key: 'totalQty', display_name: '总数量(条码数量）' },
        { key: 'finishQty', display_name: '完成数量（OK数量）' },
        { key: 'failQty', display_name: '失败数量（NG数量）' },
        { key: 'onlineQty', display_name: '在线数量' },
        { key: 'scrapQty', display_name: '报废数量' },
        { key: 'unfinishQty', display_name: '未完成数量' },
        { key: 'remark', display_name: '描述' },
        { key: 'createBy', display_name: '创建人' },
        { key: 'updateBy', display_name: '更新人' }
      ]
    }
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      this.crud.query.orderStatus = this.activeName;
      this.setStatusCount();
      return true
    },
    //新建之前
    [CRUD.HOOK.beforeToAdd]() {
      this.sections = [];
      this.crudProducts = [];
      return true
    },
    //编辑之前
    [CRUD.HOOK.beforeToEdit](crud) {
      this.lineCodeChange(crud.form.lineCode);
      this.sectionCodeChange(crud.form.sectionCode);
      return true
    },
    handleClick(value){
      this.activeName = value.name;
      this.crud.toQuery();
    },
    getOrderStatusColour(value){
      if(value == '0'){
        return 'info'
      } else if(value == '1'){
        return 'warning'
      } else if(value == '2'){
        return ''
      } else if(value == '3'){
        return 'success'
      }
      return 'info'
    },
    getProductTypeName(value){
      let name = '';
      this.productTypes.forEach(res =>{
        if(value == res.productType){
          name = res.productTypeName;
          return;
        }
      })
      return name;
    },
    //产线选择
    lineCodeChange(lineCode){
      let id = 0;
      this.lines.forEach(res => {
        if(res.modelCode == lineCode){
          id = res.id;
          return;
        }
      })
      crudFactoryModel.getModels({pid: id ,modelType: '3'}).then(res =>{
        this.sections = res.content;
      });
    },
    //工段选择
    sectionCodeChange(vaule){
      crudProductModelLien.getProductByLine({lineCode: this.crud.form.lineCode,sectionCode : vaule}).then(res =>{
        this.crudProducts = res;
      });
    },
    //产品选择
    productCodeChange(value){
      this.crudProducts.forEach(res =>{
        if(res.productCode == value){
          this.crud.form.productType = res.productType;
        }
      })
    },
    updateOrderStatus(orderStatus, order) {
      const types = {'2': '下发','1':'停止','3': '完成'};
      this.$confirm('是否'+types[orderStatus]+'该工单？', '提示', {
        confirmButtonText: '是',
        cancelButtonText: '否',
        type: 'warning'
      }).then(() => {
        const up = {
          id: order.id,
          orderStatus: orderStatus,
          workOrderCode: order.workOrderCode
        }
        crudPlanWorkOrder.edit(up).then(data =>{
          if (!data) {
            this.$notify({
              title: '成功',
              message: '状态更改成功',
              type: 'success'
            })
          }
          this.crud.toQuery()
        });
      }).catch(() => {
      })
    },
    //设置数量
    setStatusCount(){
      crudPlanWorkOrder.getStatusCount().then(res =>{
        this.statusCount = res;
      })
    }
  },
  mounted() {
    crudProductType.list().then(res =>{
      this.productTypes = res;
    })
    crudProductModel.list().then(res =>{
      this.products = res;
    });
    crudFactoryModel.getModels({modelType: '2'}).then(res =>{
      this.lines = res.content;
    });
    crudPlanOrder.list().then(res =>{
      this.orders = res;
    })
  }
}
</script>

<style scoped>

</style>
